﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：ValidPhoneAttribute.cs
// 功能描述：TongTongMall.MallWeb.Application
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace TongTongMall.MallWeb.Application.Attributes.ModelBinders
{
    public class ValidPhoneAttribute : ValidationAttribute
    {
        public bool CanNullOrEmpty { get; set; } = false;
        public ValidPhoneAttribute()
        {
            ErrorMessage = "手机号码格式不正确！";
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var result = new ValidationResult(ErrorMessage);

            if (value != null)
            {

                var strVal = value.ToString();
                if (CanNullOrEmpty)
                {
                    if (string.IsNullOrWhiteSpace(strVal))
                    {
                        return ValidationResult.Success; ;
                    }
                }
                if (Regex.IsMatch(strVal, @"^[1]{1}[3,4,5,7,8]{1}\d{9}$"))
                {
                    result = ValidationResult.Success;
                }
            }
            return result;
        }
    }
}
